import { navMenu } from "@/utils/constant/menu";
import { useMainStore } from "@/stores";
import { storeToRefs } from "pinia";
import _ from "lodash";
import {
  createRouter,
  createWebHistory,
  type RouteRecordRaw,
} from "vue-router";

const viewModules = import.meta.glob("@/views/**/*.vue");

let routes: RouteRecordRaw[] = [
  // {
  // path: "/",
  // redirect: "/home",
  // name: "home",
  // component: () => import("@/views/home.vue"),
  // },
];

const getItem = (item, isChildren) => {
  const low = item.key.toLowerCase();
  const path = `${low.indexOf("-") != -1 ? low.split("-")[1] : low}`;
  let info = {
    path: `${isChildren ? "" : "/"}${path}`,
    name: item.key,
    meta: { label: item.label, parent: item.parent || "" },
  };

  if (item.key.indexOf("Menu") != -1 && item.children?.length != 0) {
    const lowKey = item.children[0].key.toLowerCase();
    info["redirect"] = lowKey.split("-")[1];
  }
  if (item.key.indexOf("Menu") == -1) {
    const path = `/src/views/${low.replace("-", "/")}.vue`;
    info["component"] = viewModules[path];
    // info["component"] = () => import(`@/views/${low.replace("-", "/")}.vue`);
  }
  if (item.children && item.children?.length) {
    info["children"] = item.children.map((v) => {
      let items = getItem(v, true);
      return items;
    });
  }
  return info;
};
const newRoutes = _.cloneDeep(navMenu).map((v) => {
  let item = getItem(v, false);
  return item;
});

routes = routes.concat(newRoutes);

// import(`@/views/${route.componentPath}.vue`)

const router = createRouter({
  history: createWebHistory("/"),
  routes,
});

router.beforeEach((to, from, next) => {
  const stores = useMainStore();
  const { isLogin } = storeToRefs(stores);
  if (isLogin.value && to.fullPath == "/") {
    router.push("/home");
  }
  next();
});

export default router;
